/* eslint-disable vue/no-async-in-computed-properties */
<template>
    <div>
        <div class="main-head flex-between container-fluid">
            <div class="title">
                <h1 v-text="$t('pro.Library.CreativeLibrary')"></h1>
            </div>
        </div>

        <div class="content container-fluid">
            <div class="library-container grid">
                <div class="portlet">
                    <div class="grid-item folder">
                        <div class="tools" v-text="$t('pro.Library.ManageLibrary')"></div>
                        <!-- 树形文件 -->
                        <a-directory-tree defaultExpandAll>
                            <a-tree-node key="0" style="font-size: 1.4rem;color: #e8e8e8">
                 <span slot="title" style="width: 100%">{{$t('pro.Library.CreativeLibrary')}}&nbsp;
                     <a-button
                             type="primary"
                             shape="circle"
                             size="small"
                             icon="plus"
                             style="float: right"
                             @click.stop.nactve="addFolderClick(0)"
                     />
                 </span>
                                <a-tree-node
                                        :key="item.id"
                                        v-for="(item, key) in fileList"
                                >
                  <span slot="title">{{item.fileName}}&nbsp;
                    <a-button
                            shape="circle"
                            size="small"
                            @click.stop="editFolderClick(item)"
                            icon="edit"
                            class="ant-btn-dsp-edit"
                            style="float: right;margin-left: 8px"
                    />
                    <a-button
                            type="danger"
                            shape="circle"
                            size="small"
                            @click.stop="deleteFolder(item)"
                            icon="delete"
                            style="float: right;margin-left: 8px"
                    />
                     <a-button
                             type="primary"
                             shape="circle"
                             size="small"
                             icon="plus"
                             style="float: right"
                             @click.native.stop="viewFile(item)"
                     />
                  </span>
                    <a-tree-node
                            @click.native.stop="viewerImg(item2)"
                            v-if="!!item.fileManagers"
                            :key="item2.id"
                            v-for="(item2) in item.fileManagers"
                            isLeaf>
                                <span slot="title">
                                   <span style="width: 72%;display: inline-block;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">{{item2.fileName}}&nbsp</span>
                                   <a-button
                                           shape="circle"
                                           size="small"
                                           @click.stop="editFileClick(item2)"
                                           icon="edit"
                                           class="ant-btn-dsp-edit"
                                           style="float: right;margin-left: 10px"
                                   />
                                   <a-button
                                           type="danger"
                                           shape="circle"
                                           size="small"
                                           @click.stop="deleteFile(item2)"
                                           icon="delete"
                                           style="float: right"
                                   />
                                </span>
                     </a-tree-node>
                 </a-tree-node>
               </a-tree-node>
              </a-directory-tree>
              </div>
            </div>

            <!-- 左边显示区-->
            <div class="portlet m-left-14" >
                <div class="grid-item file">
                        <!--$t('pro.Library.Preview')-->
                        <div class="tools">
                            <strong v-text="$t('pro.Library.Name')"></strong>
                            <p style="word-wrap:break-word;word-break:normal;">{{ viewerOsInfo.fileName }}</p>
                            <span v-show="viewerOsInfo.fileType && viewerOsInfo.fileType.indexOf('image') !== -1"> ({{viewerOsInfo.width}} x {{viewerOsInfo.height}})</span>
                        </div>
                        <a-skeleton active :loading="fileLoad">
                            <div style="padding: 10px 10px 20px 10px">
                                <div class="file-view-box">
                                    <a-spin :spinning="imgloading" :tip="$t('pro.public.loading')">
                                        <a-card v-if="viewerOsInfo.fileType && viewerOsInfo.fileType.indexOf('image') !== -1">
                                            <img
                                                :alt="viewerOsInfo.alt"
                                                :src="viewerOsInfo.displayPath"
                                                slot="cover"
                                                @load="getImage()"
                                            />
                                        </a-card>

                                        <video v-else-if="viewerOsInfo.fileType && viewerOsInfo.fileType.indexOf('video') !== -1" controls>
                                            <source :src="viewerOsInfo.displayPath" :type="viewerOsInfo.fileType">
                                        </video>

                                        <a-skeleton v-else/>
                                    </a-spin>
                                </div>

                                
                                <p class="m-b-10px file-herf">
                                     <a-tooltip placement="top">
                                        <template slot="title">
                                            {{viewerOsInfo.href}}
                                        </template>
                                        <strong v-text="$t('pro.Library.URL')"></strong>
                                        <span>
                                            {{viewerOsInfo.href}}
                                        </span>
                                     </a-tooltip>
                                </p>
                            </div>
                        </a-skeleton>
                    </div>


             </div>
            </div>

        </div>

        <a-modal
                :title="modalMsg"
                v-model="modalVisible"
                @ok="handleSaveOk"
                @cancel="hideModal"
                :confirmLoading="confirmLoading"
                :okText="isAddDirectory? this.$t('pro.Library.AddDirectory'):this.$t('pro.public.buttonSave')"
                :cancelText="this.$t('pro.public.buttonClose')"
        >
            <!-- 改变文件夹名的部分 -->
            <template v-if="isChangeFolderName">
                <p v-text="$t('pro.Library.NewDirectory')"></p>
                <a-input v-model="newFolderName" @pressEnter="handleSaveOk"/>
                <p v-if="sameName" class="notify" v-text="$t('pro.Library.ExistingDirectory')"></p>
            </template>

            <!-- 编辑文件信息的部分 -->
            <template v-else-if="isEditFile">
                <a-form-item :label="$t('pro.Library.Name')">
                    <a-input v-model="editingFile.fileName"/>
                </a-form-item>

                <p v-if="sameName" class="notify" v-text="$t('pro.Library.ExistingDirectory')"></p>
                <a-form-item :label="$t('pro.UploadFile.ReferenceURL')">
                    <a-input v-model="editingFile.href"/>
                </a-form-item>
                <a-form-item :label="$t('pro.UploadFile.AlterText')">
                    <a-input v-model="editingFile.alt"/>
                </a-form-item>
            </template>

            <!-- 新增文件夹的部分 -->
            <template v-else>
                <p v-text="$t('pro.Library.EnterDirectory')"></p>
                <a-input v-model="newFolderName" @pressEnter="handleSaveOk"/>
                <p v-if="sameName" class="notify">
                    {{$t('pro.Library.ExistingDirectory')}}
                    <span>{{correct}}</span>
                </p>
            </template>

        </a-modal>
    </div>
</template>

<script>
    import {
        getFileManager,
        addFileManager,
        setFileManager,
        deleteFileManager,
        editFiles
    } from "@/api/file-manager";

    export default {
        name: "TreeList",
        data() {
            return {
                // 文件夹列表
                fileList: [],
                // 展示给用户看到的文件列表
                renderFileList: [],
                modalVisible: false,
                newFolderName: "",
                sameName: false,
                correct: "",
                spinningFile: false,


                imgloading: false,
                editFolderID: null,
                editingFile: {
                    fileName: "",
                    href: "",
                    alt: ""
                },
                compareFileDetail: {},
                // 在对话框关闭的时候()初始化下列三个值为false
                // 1.是编辑文件的对话框
                isEditFile: false,
                // 2.是添加文件夹的对话框
                isAddDirectory: false,
                // 3.是改变文件夹的对话框
                isChangeFolderName: false,
                // 对话框
                confirmLoading: false,
                parentDirectoryId: 0, //上级文件ID 0=根目录

                fileBoxPreview: false,
                fileLoad: false,
                viewerOsInfo: {
                    alt: '',
                    displayPath: '',
                    href: '',
                    fileName: '',
                    id: '',
                    height: '',
                    width: '',
                    fileType: ''
                },
            };
        },
        computed: {
            modalMsg() {
                return this.isChangeFolderName
                    ? this.$t('pro.Library.ChangeDirectory')
                    : this.isEditFile
                        ? this.$t('pro.Library.EditImage')
                        : this.$t('pro.Library.AddDirectoryName');
            },
        },
        methods: {
            viewerImg(obj) {
                //子文件点击打开资源显示：filePreview
                this.fileBoxPreview = true;

                this.fileLoad = true;
                this.viewerOsInfo = {};
                setTimeout(() => {
                    this.fileLoad = false;
                    this.viewerOsInfo = obj;
                }, 600)

            },

            viewFile(file) {
                this.$router.push("/bidder/uploadfile/folderid/" + file.id);
                this.fileBoxPreview = false;
            },

            //获取图片是否加载完毕
            getImage() {
                this.imgloading = false
            },

            getRefresh() {
                this.fileList = [];
                getFileManager()
                    .then(res => {
                        this.fileList = res.data.data;
                    })
            },

            // [修改文件夹名] 保存信息的操作
            editFolder() {
                if (!!this.newFolderName && this.newFolderName.length <= 10) {
                    // 已存在的文件夹名列表
                    const folderNames = this.fileList.map(folder => folder.fileName);
                    // 判断是否存在同名文件夹
                    this.sameName = folderNames.some(name => this.newFolderName == name);

                    if (!this.sameName) {
                        let fileManager = new Object();
                        fileManager.id = this.editFolderID;
                        fileManager.fileName = this.newFolderName;
                        setFileManager(fileManager)
                            .then(res => {
                                if (res.data.data) {
                                    this.getRefresh();
                                }
                            })
                    }
                }else {
                    this.$message.warning(this.$t('pro.UploadFile.tipsLen'))
                }


            },

            // [修改文件夹名] 点击图标弹出对话框的操作
            editFolderClick(folder) {
                if (!!folder.fileName && folder.fileName.length > 0) {
                    this.isChangeFolderName = true;
                    this.newFolderName = folder.fileName;
                    this.editFolderID = folder.id;
                    this.showMadal();
                }else {
                    this.$message.warning(this.$t('pro.UploadFile.tipsLen2'))
                }

            },

            deleteFolder(folder) {
                const [folderID, folderKey] = [Number(folder.id), Number(folder.fileKey)];
                const fileCount = folder.fileManagers
                    ? Array.isArray(folder.fileManagers)
                        ? folder.fileManagers.length
                        : 0
                    : 0;
                this.$confirm({
                    title: this.$t('pro.Library.delFolde') + `<${folder.fileName}> ?`,
                    content:
                        fileCount > 0
                            ? this.$t('pro.Library.ClearAllFolders')
                            : this.$t('pro.Library.emptyfolder'),
                    okText: this.$t('pro.public.buttonYes'),
                    okType: fileCount > 0 ? "danger" : "",
                    cancelText: this.$t('pro.public.buttonNo'),
                    // 这儿执行删除文件夹的操作
                    // 可能用到的值`folderID`,`folderKey`
                    onOk: () => {
                        deleteFileManager(folderID)
                            .then(res => {
                                if (res.data.data) {
                                    this.getRefresh();
                                }
                            })
                    },
                    onCancel() {}
                });
            },

            // [添加文件夹] 提交的操作
            addFolder() {
                // 已存在的文件夹名列表
                const folderNames = this.fileList.map(folder => folder.fileName);
                // 将要创建的文件夹名
                const folderName = this.createName(this.newFolderName, folderNames);
                console.log(folderName);

                if (!!folderName && folderName.length <= 10) {
                     this.sameName = folderNames.includes(this.newFolderName);
                    this.correct = folderName;

                    let fileManager = new Object();
                    fileManager.parentDirectoryId = this.parentDirectoryId || 0;
                    fileManager.fileName = folderName;

                    fileManager.fileKey = 0;
                    if (this.fileList.length > 0) {
                        fileManager.fileKey = Number(this.fileList[this.fileList.length - 1].fileKey) + 1;
                    }

                    addFileManager(JSON.stringify(fileManager))
                        .then(res => {
                            if (res.data.data) {
                                this.getRefresh();
                            }
                        })
                        .catch(error => {
                            console.log(error);
                        });
                }else {
                    this.$message.warning(this.$t('pro.UploadFile.tipsLen'))
                }

            },

            // [添加文件夹] 点击弹出对话框的操作
            addFolderClick(parentId) {
                this.parentDirectoryId = parentId;
                this.isAddDirectory = true;
                this.newFolderName = "";
                this.showMadal();
            },

            // [编辑文件信息] 保存
            editFile() {
                console.log(this.editingFile);
                if (!!this.editingFile.fileName && this.editingFile.fileName.length > 0) {
                    editFiles(this.editingFile)
                        .then(res => {
                            if (res.data.data) {
                                this.getRefresh();
                            }
                        })
                }else {
                    this.$message.warning(this.$t('pro.UploadFile.tipsLen2'))
                }

            },

            // [编辑文件信息] 点击弹框
            editFileClick(file) {
                this.isEditFile = true;
                this.editingFile = {
                    id: file.id,
                    fileName: file.fileName,
                    href: file.href,
                    alt: file.alt
                };
                this.compareFileDetail = file;
                this.showMadal();
            },

            //子文件删除
            deleteFile(file) {
                this.$confirm({
                    title: this.$t('pro.Library.delTitle'),
                    content: `${file.fileName}`,
                    okText: this.$t('pro.public.buttonYes'),
                    okType: "danger",
                    cancelText: this.$t('pro.public.buttonNo'),
                    onOk: () => {
                        this.spinningFile = true;
                        deleteFileManager(file.id)
                            .then(res => {
                                if (res.data.data) {
                                    //成功清空数据 重新查
                                    this.viewerOsInfo = {};
                                    this.getRefresh();
                                }
                            })
                            .finally(() => {
                                this.spinningFile = false
                            });
                    },
                    onCancel() {
                    }
                });
            },
            //判断文件目录是否为空 通过验证执行的函数
            isDirectoryNull(fun) {
                if (!this.newFolderName.trim() && this.newFolderName.trim().length <= 0) {
                    this.$message.warning(this.$t('pro.Library.directoryNameIsNull'));
                    this.modalVisible = false;
                    return false
                } else {
                    fun();
                }
            },

            // 对话框信息保存
            handleSaveOk() {
                this.confirmLoading = true;
                //判断是否修改
                if (this.isEditFile) {
                    this.editFile();
                }

                /*添加目录*/
                if (this.isAddDirectory) {
                    //判断目录是为空
                   this.isDirectoryNull(this.addFolder);
                }
                /*修改目录*/
                if (this.isChangeFolderName) {
                    this.isDirectoryNull(this.editFolder);
                }

                const doHide = (this.isChangeFolderName && !this.sameName) || !this.isChangeFolderName;
                if (doHide) {
                    setTimeout(() => {
                        this.hideModal();
                    }, this.sameName ? 1500 : 0);
                }
            },

            // 对话框隐藏
            hideModal() {
                this.modalVisible = false;
                setTimeout(() => {
                    this.isEditFile = false;
                    this.isAddDirectory = false;
                    this.isChangeFolderName = false;
                    this.confirmLoading = false;
                }, 850);
            },

            // 显示对话框
            showMadal() {
                this.modalVisible = true;
                this.sameName = false;
            },

            // 解决文件(夹)同名问题  ----(待修改：判断同明且长度在9位的名字。提示不能同名)
            createName(newName, names) {
                /**
                 * @param newName {String}
                 * @param names {Array}
                 */
                let val = names.includes(newName) ? `${newName}-1` : `${newName}`;

                if (names.includes(newName)) {
                    return this.createName(val, names);

                }else if(names.includes(newName)) {
                    return this.createName(val, names);

                }else {
                    return val;
                }
            }
        },
        mounted() {
            this.getRefresh();
        },
    };
</script>

<style lang="less">
    @hover-bgcolor: #1da57a;

    .m-left-14 {
        margin-left: 14px;
    }

    .library-container.grid {
        grid-template-columns: 1fr 2fr;
        grid-gap: 1px;
        .folder {
            padding-right: 15px;
        }
        .file {
            padding-left: 15px;
        }
    }

    @media screen and (max-width: 1167px) {
        .library-container.grid {
            display: block;
            .folder {
                padding-right: 0;
                margin-bottom: 1.5em;
            }
            .file {
                padding-left: 0;
            }
            .m-left-14 {
                margin-left: 0;
                margin-top: 20px;
            }
        }
    }

    .file-list {
        display: flex;
        align-items: center;
        margin-bottom: 1em;
        padding-bottom: 20px;
        word-break: break-all;
    }

    @media screen and (max-width: 640px) {
        .file-list {
            display: block;
            > div:last-child {
                margin-left: 0;
            }
        }
    }

    .m-b-10px {
        margin-top: 10px;
    }
    .file-view-box {
        .ant-card-cover {
            max-height: 410px!important;
        }
    }

</style>

<style lang="less" scoped>
    .file-view-box {
        width: 100%;
        max-height: 440px;overflow: auto;

    }
    .file-herf {
        float:right;overflow: hidden;max-width: 84%;white-space: nowrap;text-overflow: ellipsis;
    }
</style>
